# 定义treeNode类，用来保存树的每一个节点
class treeNode:
    def __init__(self, nameValue, numOccur, parentNode):
        self.name = nameValue
        self.count = numOccur
        self.nodeLink = None
        self.parent = parentNode      #needs to be updated
        self.children = {} 
    
    def inc(self, numOccur):
        self.count += numOccur
        
    def disp(self, ind=1):
        print ('  '*ind, self.name, ' ', self.count)
        for child in self.children.values():
            child.disp(ind+1)

# 构建FP树
def createTree(dataSet, minSup=1): # 使用数据集以及最小支持度作为参数来构建FP树
    headerTable = {}        # 创建一个空的头指针表headerTable
    # 遍历数据集两次
    for trans in dataSet:   # 第一次遍历，统计每个元素出现的频度
        for item in trans:
            headerTable[item] = headerTable.get(item, 0) + dataSet[trans]
    for k in list(headerTable.keys()):  # 移除不满足最小支持度的元素项
        if headerTable[k] < minSup: 
            del(headerTable[k])
    freqItemSet = set(headerTable.keys())           # 取头指针表headerTable中key的集合
    #print ('freqItemSet: ',freqItemSet)
    if len(freqItemSet) == 0: return None, None     # 如果没有元素项满足要求，则退出
    for k in headerTable:               # 扩展头指针表，以便可以保存指向每种类型第一个元素项的指针
        headerTable[k] = [headerTable[k], None] 
    #print ('headerTable: ',headerTable)
    retTree = treeNode('Null Set', 1, None) # 创建树，只包含空集合的根节点
    for tranSet, count in dataSet.items():  # 第二次遍历，根据全局频数对每个事务中的元素进行排序
        localD = {} # 构造一个空字典
        for item in tranSet:  # 将headerTable中各元素的频数存到字典localD中
            if item in freqItemSet:
                localD[item] = headerTable[item][0]
        if len(localD) > 0: 
            orderedItems = [v[0] for v in sorted(localD.items(), key=lambda p: p[1], reverse=True)] # 排序
            updateTree(orderedItems, retTree, headerTable, count)   # 使用排序后的频率项集对树进行填充
    return retTree, headerTable         # 返回FP树retTree和头指针表headerTable

# 使用排序后的频率项集对树进行填充
# 输入参数，排序后的平率项集items、树inTree、头指针表headerTable和计数值count
def updateTree(items, inTree, headerTable, count):
    if items[0] in inTree.children: # check if orderedItems[0] in retTree.children
        inTree.children[items[0]].inc(count) # 增加计数
    else:   # add items[0] to inTree.children
        inTree.children[items[0]] = treeNode(items[0], count, inTree)
        # 更新头指针表
        if headerTable[items[0]][1] == None: 
            headerTable[items[0]][1] = inTree.children[items[0]]
        else:
            updateHeader(headerTable[items[0]][1], inTree.children[items[0]])
    #递归调用updateTree()函数，每次迭代会去掉items列表中的第一个元素，直到items列表中只剩最后一个元素为止
    if len(items) > 1:  
        updateTree(items[1::], inTree.children[items[0]], headerTable, count)

# 更新头指针表函数        
def updateHeader(nodeToTest, targetNode):   #this version does not use recursion
    while (nodeToTest.nodeLink != None):    #Do not use recursion to traverse a linked list!
        nodeToTest = nodeToTest.nodeLink
    nodeToTest.nodeLink = targetNode

# 发现以给定元素项结尾的所有路径的函数
def ascendTree(leafNode, prefixPath): # 遍历链表直到到达结尾
    if leafNode.parent != None:
        prefixPath.append(leafNode.name)    
        ascendTree(leafNode.parent, prefixPath)     # 迭代上溯整棵树
    
def findPrefixPath(basePat, treeNode): #treeNode comes from header table
    condPats = {}           # 构造一个空的条件模式基字典
    while treeNode != None: # 当树节点部位空时
        prefixPath = []     # 构造一个空的路径列表
        ascendTree(treeNode, prefixPath)        # 发现以treeNode节点元素结尾的所有路径
        if len(prefixPath) > 1: 
            condPats[frozenset(prefixPath[1:])] = treeNode.count
        treeNode = treeNode.nodeLink
    return condPats # 返回条件模式基字典condPats

# 递归查找频繁项集的mineTree函数
# 输入参数，FP树inTree、头指针表headerTable
def mineTree(inTree, headerTable, minSup, preFix, freqItemList):
    bigL = [v[0] for v in sorted(headerTable.items(), key=lambda p: p[1][0])] # 对头指针表中的元素项按照其出现频率进行从小到大排序
    for basePat in bigL:  # start from bottom of header table
        newFreqSet = preFix.copy()
        newFreqSet.add(basePat)
        #print ('finalFrequent Item: ',newFreqSet )   #append to set
        freqItemList.append(newFreqSet)
        condPattBases = findPrefixPath(basePat, headerTable[basePat][1]) 
        #print ('condPattBases :',basePat, condPattBases)
        myCondTree, myHead = createTree(condPattBases, minSup) # 从条件模式基来构建条件FP树
        #print ('head from conditional tree: ', myHead)
        if myHead != None: # 挖掘条件FP树
            print ('conditional tree for: ',newFreqSet)
            myCondTree.disp(1)            
            mineTree(myCondTree, myHead, minSup, newFreqSet, freqItemList) # 递归调用mineTree()函数

# 构造一个简单数据集
def loadSimpDat():
    simpDat = [['r', 'z', 'h', 'j', 'p'],
               ['z', 'y', 'x', 'w', 'v', 'u', 't', 's'],
               ['z'],
               ['r', 'x', 'n', 'o', 's'],
               ['y', 'r', 'x', 'z', 'q', 't', 'p'],
               ['y', 'z', 'x', 'e', 'q', 's', 't', 'm']]
    return simpDat

# 将数据集包装为frozenset型的数据
def createInitSet(dataSet):
    retDict = {}
    for trans in dataSet:
        retDict[frozenset(trans)] = 1
    return retDict

